package Netty_basic;


import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import jdk.jfr.events.SocketReadEvent;

//Channel
//close方法关闭channel
//closeFuture用来处理channel的关闭，sync方法是同步等待channel关闭，addlistner是异步等待channel关闭
//pipeline方法添加处理器
//write方法写入输入到缓冲区
//writeAndFlush是写入并立即从缓冲区刷出去
public class element_Channel {
    public static void main(String[] args) {
        Client2();
    }

    /*
    服务器结果

    main:[id: 0xf4baee48]             //代表此时还没成功建立连接
    [id: 0xf4baee48, L:/127.0.0.1:50725 - R:localhost/127.0.0.1:8080]  //成功建立连接，返回了一个四元组
    连接建立！
     */
    public static void Client2(){
        ChannelFuture cf = new Bootstrap()
                .group(new NioEventLoopGroup())
                .channel(NioSocketChannel.class)
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {
                        ch.pipeline().addLast(new StringDecoder());
                    }
                }).connect("localhost", 8080);//注意，这里的connect方法是异步的！

        //除了使用sync方法同步异步操作外，还可以addListener
        cf.addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture future) throws Exception {
                System.out.println(future.channel());
                System.out.println("连接建立！");
            }
        });
        System.out.println(Thread.currentThread().getName()+":"+cf.channel());



    }
}
